package com.yanftch.stopcoding.request;

import com.alibaba.fastjson2.JSONObject;
import com.yanftch.stopcoding.bean.HotBean;
import com.yanftch.stopcoding.bean.TouTiao;
import com.yanftch.stopcoding.bean.ZhiHu;
import com.yanftch.stopcoding.cb.RequestCallBack;
import com.yanftch.stopcoding.common.network.CallBack;
import com.yanftch.stopcoding.common.network.HttpUtils;
import com.yanftch.stopcoding.common.util.TextUtils;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

public class ZhihuHotRequest implements Request {

    private static final String ZHIHU_URL = "https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=100";

    public interface ZhihuHotCallBack {
        void onSuccess(ArrayList<HotBean> list);

        void onError(Exception e);
    }

    @Override
    public void request(RequestCallBack callBack) {
        getZhihuHotList(new ZhihuHotCallBack() {
            @Override
            public void onSuccess(ArrayList<HotBean> list) {
                if (callBack != null) callBack.onSuccess(list);
            }

            @Override
            public void onError(Exception e) {
                if (callBack != null) callBack.onError(e);
            }
        });
    }

    private void getZhihuHotList(@NotNull ZhihuHotCallBack zhihuHotCallBack) {
        HttpUtils.get(ZHIHU_URL, new CallBack() {
            @Override
            public void onSuccess(String response) {
                if (TextUtils.isEmpty(response)) {
                    zhihuHotCallBack.onError(new Exception("response is empty"));
                    return;
                }
                ZhiHu zhiHu = JSONObject.parseObject(response, ZhiHu.class);
                ArrayList<HotBean> list = new ArrayList<>();
                if (zhiHu != null && zhiHu.getData() != null && !zhiHu.getData().isEmpty()) {
                    for (ZhiHu.DataBeanX datum : zhiHu.getData()) {
                        HotBean hotBean = new HotBean();
                        hotBean.setTitle(datum.getTarget().getTitle());
                        hotBean.setUrl("https://www.zhihu.com/question/" + datum.getTarget().getId());
                        list.add(hotBean);
                    }
                    zhihuHotCallBack.onSuccess(list);
                } else {
                    zhihuHotCallBack.onError(new Exception("知乎API路径变了，找插件开发者更新吧~"));
                }
            }

            @Override
            public void onError(Exception e) {
                zhihuHotCallBack.onError(e);
            }
        });
    }

    public static void main(String[] args) {
//        getZhihuHotList(new ZhihuHotCallBack() {
//            @Override
//            public void onSuccess(ArrayList<HotBean> list) {
//                for (HotBean bean : list) {
//                    System.out.println(bean);
//                }
//            }
//
//            @Override
//            public void onError(Exception e) {
//
//            }
//        });

    }
}
